package com.wt.springsamples.tx;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 本地事务失效时：原理，调用自身方法时，被调用的方法没有通过代理对象调用，导致Aop失效，
 * 解决办法：
 *  1、引入spring-boot-starter-aop包
 *  2、开启Aspectj代理功能，@EnableAspectJAutoProxy(exposeProxy = true)
 *  3、方法内部使用代理对象调用本类方法
 *    TxService txService = (TxService) AopContext.currentProxy();
 *
 */
@Service
public class TxService{

    public TxService() {
        System.out.println("TxService init");
    }

    @Autowired
    private UserService userService;
    @Autowired
    TxService txServiceProxy;

    @Autowired
    private TxDao txDao;

    @Transactional
    public  void test(){
        txDao.add();
    }

    @Transactional(propagation= Propagation.REQUIRED,timeout = 2)
    public  void save(){
        System.out.println("save called ");
        userService.update();
        TxService txService = (TxService) AopContext.currentProxy();
//        UserModel userModel = txServiceProxy.get(1);
//        if(userModel==null){
//            txServiceProxy.add();
//        }else {
//            txServiceProxy.update();
//        }
    }

    @Transactional(propagation= Propagation.REQUIRES_NEW,timeout = 2)
    public  void add(){
    }

    @Transactional(propagation= Propagation.NESTED)
    public  void update(){
    }

    @Transactional(propagation= Propagation.SUPPORTS)
    public  void delete(){
    }

    @Transactional(propagation= Propagation.NEVER)
    public UserModel get(Integer id){
       return new UserModel();
    }

}
